Day 9 - January 6, 2018

Problem 24 A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012 021 102 120 201 210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? Note: What permutation changes the


In [53]:
%%timeit
import itertools as i 
a = [x for x in  i.permutations(range(10))]
value = a[1000000]


1 loop, best of 3: 1.1 s per loop

In [33]:
moo = ''
for x in a[1000000]: 
    moo = moo + str(x)
print(moo)


2783915604

In [52]:
%%timeit
# with math 
import math
alist = [0,1,2,3,4,5,6,7,8,9]
value = ''
remain = 1000000
for x in range(9,0,-1):
    boo = math.factorial(x)
    place = (math.floor(remain / boo))
    value = value + str(alist[place])
    alist.pop(place)
    remain = remain % boo
value = value + str(alist[0])
# print(value)


10000 loops, best of 3: 30.5 µs per loop

Day 8 - January 4, 2018

Problem 23 A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.


In [30]:
smallest = 24  # 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16 
biggest = 28123 #  28123 can be written as the sum of two abundant numbers 

theabuns, allnum = set(), set()

total = 0 
def isAbundant(num):
    count, facty = 0, 1 
    divisors = set()
    for x in range(1,num):
        if num % x == 0:
            divisors.add(x)
    if sum(divisors) > num:
        return(True)
    return(False)

print(isAbundant(12))
for a in range(11, biggest):
    if isAbundant(a):
        theabuns.add(a)
for a in theabuns:
    for b in theabuns:
        allnum.add(a+b)
for a in range(1, biggest):
    if a not in allnum:
        total = total + a
print(total)


True
4179871

In [29]:
for a in range(1,smallest):
    total = total + a 
print(total)


4179871

Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?


In [52]:
path = 'p022_names.txt'
with open(path, 'r') as file:
    content = file.read().rsplit(',')
for key, value in enumerate(content):
    content[key] = value.strip('/"')
content = sorted(content)
#print(content)
total = 0 
for key, value in enumerate(content):
    namescore = 0 
    for x in value:
        namescore = namescore + ord(x) - 64
    # print("The value of ", value, " is ",namescore, (namescore * (key+1)) )
    total = total + (namescore * (key+1))
print("Sum of the value of the names * order)", total)


Sum of the value of the names * order) 871198282

Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000. Note: https://en.wikipedia.org/wiki/Amicable_numbers


In [17]:
def d(num):
    boo = set()
    total = 0
    for x in range(1,num):
        if num % x == 0:
            boo.add(x)
    for x in boo:
        total = total + int(x)
    return(total)   
top = 10000 
divisorsums = set()
sumofall = 0 
for y in range(1,top):
    temp = d(y)
    divisorsums.add(temp)     # there will be 10k-ish in here 
    if y in divisorsums:
        if y == d(temp) and y != temp:
            print(" We really found one",y, temp)
            sumofall = sumofall + y + temp
print(sumofall)


 We really found one 284 220
 We really found one 1210 1184
 We really found one 2924 2620
 We really found one 5564 5020
 We really found one 6368 6232
31626

Day 7 - January 3, 2018

Problem 20 n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!


In [88]:
%%timeit
import math 
num = 100
#num = 10
count = 0 
for x in str(math.factorial(num)):
    count = count + int(x)
#print(count)


10000 loops, best of 3: 68.9 µs per loop

In [99]:
%%timeit
num = 101
# num = 10
count, facty = 0, 1 
for x in range(1,num):
    facty = facty * x
for x in str(facty):
    count = count + int(x)
#print(count)


10000 loops, best of 3: 74.5 µs per loop

Problem 19 You are given the following information, but you may prefer to do some research for yourself.

  • 1 Jan 1900 was a Monday.
  • Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? Note: Should I do this with no libraries?


In [83]:
import calendar as c
Sunday = 6
count = 0 
print("Is 1 Jan a Monday (0)?", c.weekday(1900,1,1))
for year in range(1901,2001):
    for month in range(1,13):
        if c.weekday(year,month,1) == Sunday:
            count = count + 1
print("Total Sunday on the 1st of the month(1901 to 2000)", count)


Is 1 Jan a Monday (0)? 0
Total Sunday on the 1st of the month(1901 to 2000) 171

Problem 18 and 67 By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3 7 4 2 4 6 8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)


In [70]:
import sys
path = 'p18b.txt'
total, most = 0, 0 
tower,distance = [], []
with open(path, 'r') as file:
    content = file.read().splitlines()
    for x in content:
        tower.append(x.rsplit())
# print(tower)
for row, value in enumerate(tower):
    distance.append([0]* len(value))
    for col, node in enumerate(value):
        if col < len(value)-1 :
            vmom = distance[row-1][col]
        else: 
            vmom = 0
            # print("There is no mom (to the right) ")
        if (col - 1) >= 0:
            vdad = distance[row-1][col-1]
        else: 
            vdad = 0 
            # print("There is no dad (to the left) ")
        distance[row][col] = max(vdad, vmom) + int(node)

# print(distance)
print(max(distance[len(distance)-1]))


7273

Day 6 - January 2, 2018

Problem 17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. Note: Feels like a dictionary - https://www.ego4u.com/en/cram-up/vocabulary/numbers/cardinal Not: 21145, 21121 Answer = 21124


In [60]:
cardinal = {0: '',1:'one', 11:'eleven', 2:'two', 12:'twelve',40:'forty',3:'three', 13:'thirteen', 50:'fifty', 4:'four', 14:'fourteen',
60:'sixty',
5:	'five',
15:	'fifteen',
70:'seventy',
6:	'six',
16:	'sixteen',
80:'eighty',
7:	'seven',
17:	'seventeen',
90:'ninety',
8:	'eight',
18:	'eighteen',
100:'hundred',
9:	'nine',
19:	'nineteen',
1000:'onethousand',
10:'ten',
20:'twenty',
30:'thirty'}
print(cardinal)
num = 342
print(cardinal[((num - (num % 100))/100)])


{0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 70: 'seventy', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 80: 'eighty', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 90: 'ninety', 30: 'thirty', 16: 'sixteen', 100: 'hundred', 6: 'six', 40: 'forty', 1000: 'onethousand', 50: 'fifty', 60: 'sixty'}
three

In [77]:
top = 22 
total = 0 
def gettens(num):
    if num in cardinal: 
        return(len(cardinal[num]))
    onesplace = num % 10 
    tensplace = num - (num % 10)
    sum  =len(cardinal[tensplace]) + len(cardinal[onesplace])
    return(sum)
def gethundreds(num):
    sum = len(cardinal[((num - (num % 100))/100)]) 
    sum = sum + len(cardinal[100])
    tens = (num % 100)
    if tens != 0:
        sum = sum + 3    # and 
        sum = sum + gettens(tens)
    return(sum)
bot  = 1
top = 1000
total = 0  
just = 0 
for x in range(bot,top+1):
    if x in cardinal: 
        total = total + len(cardinal[x])
        if x == 100: 
            total = total + 3 
        just = len(cardinal[x])
    elif x > 20 and x < 100: 
        total = total + gettens(x)
        just = gettens(x)
    elif x > 100 and x < 1000:
        total = total + gethundreds(x)
        just = gethundreds(x)
    else: 
        print("oops, too high or too wrong", x)  

print("Total: ", total)
print(cardinal)


Total:  21124
{0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 70: 'seventy', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 80: 'eighty', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 90: 'ninety', 30: 'thirty', 16: 'sixteen', 100: 'hundred', 6: 'six', 40: 'forty', 1000: 'onethousand', 50: 'fifty', 60: 'sixty'}

In [18]:
cardinal = {1:	'one', 11:'eleven', 2:'two', 12:'twelve',40:'forty',3:'three', 
13:	'thirteen'	
50	'fifty'
4:	'four'	
14:	'fourteen'	
60	'sixty'
5:	'five'	
15:	'fifteen'	
70	'seventy'
6:	'six'	
16:	'sixteen'	
80	'eighty'
7:	'seven'	
17:	'seventeen'
90	'ninety'
8:	'eight'	
18:	'eighteen'
100	'onehundred'
9:	'nine'	
19:	'nineteen'
1,000	'onethousand'
10:	'ten'	
20:	'twenty'	
30	'thirty'


ten

Problem 16 215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?


In [14]:
x = 1000
value = 2**x
print("Two raised to the  ", x, " : ",value )
total = 0
for y in str(value):
    total = total + int(y )
print("   The sum of the digits is ", total)


Two raised to the   1000  :  10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
   The sum of the digits is  1366

Day 5 - January 1, 2018

Problem 15 Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.

How many such routes are there through a 20×20 grid? Note: Is this a recurssion? Is this just math? Steps = N * 2 (so 2 will have 4 steps and 20 will have 40 steps . Half will be over, half down. Order will not matter Thank you : https://www.youtube.com/watch?v=M8BYckxI8_U


In [125]:
import math
size = 20
count = 0 
num = math.factorial(size*2)
dem = math.factorial(size) * math.factorial(size)
print(num/dem)


5919012181389927685417441689600000000
137846528820.0

Problem 14 The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even) n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million. MyNOTE: Start from 1? Every number is in a set (ie 13 is always with 40, etc) Use recurssion to find the sets but do we really have to ... A MILLION TIMES? The right answer is 837,799 (from wikipedia) with 524 steps.


In [74]:
# This is slow. Too slow 
def getCollatz(num):
    seq = set()
    seq.add(num)
    if num == 1:
        return(seq)
    else:
        if num % 2 == 0:
            temp = int(num/2)
        else: 
            temp = int((3 * num) + 1 )
        seq.update(getCollatz(temp))
    return(seq)

seed = 999999
end = 99999
high, bigdog = 0 , 0 
for x in range(seed,end,-2):
    total = len(getCollatz(x))
    if total > high:
        bigDog = x
        high = total
print(bigDog, high)


837799 525

In [101]:
# For speed, find them once and save them. But which ones? A million
seed = 1000000
million = [0 for x in range(seed)]
million[1] = 1
million[0] = 1
high = 0 
def getCollatzSize(num):
    if num < seed:
        if million[num] != 0:
            return(million[num])
        else: 
            if num % 2 == 0:
                temp = int(num/2)
            else: 
                temp = int((3 * num) + 1) 
            million[num] = getCollatzSize(temp) +1 
            return(million[num])
    else: 
        if num % 2 == 0:
            temp = int(num/2)
        else: 
            temp = int((3 * num) + 1) 
        return(getCollatzSize(temp) +1 )    
for x in range(seed):
    getCollatzSize(x)
top = max(million)
print(million.index(top))


837799

Problem 13 Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.


In [34]:
path = 'p13.txt'
total = 0 
with open(path, 'r') as file:
    content = file.read().splitlines()
for x in content:
    value = int(x)
    total = total + value
print(total)
print(str(total)[:10])


5537376230390876637302048746832985971773659831892672
5537376230

Day 4 - December 31

Problem 12 The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors? Rule : n(n+1)/2 = is the value of the nth triangle number (5th = 5(5+1)/2 = 15 (https://www.mathsisfun.com/algebra/triangular-numbers.html) Note: Every other one is a 'triagular number 1,6,15,28 ...) Note: every triangular number is either divisible by three or has a remainder of 1 when divided by 9


In [50]:
import math
stillLooking = True
x, trinum = 1, 0 
divisor = 500
# divisor = 5
def numberofFactors(num):
    upto = int(math.sqrt(num) + 1)
    total = 0
    temp = set()
    for x in range(1,upto):
        if num % x == 0:
            temp.add(x)
            temp.add(int(num/x))
    return(len(temp))
while stillLooking:
    trinum = int((x*(x+1))/2)
    if numberofFactors(trinum) > divisor:
        stillLooking = False
        print("You did it! ")
    else:
        x = x + 1 
print("The nth triangle number with over 500 is ", x, trinum)


You did it! 
The nth triangle number with over 500 is  12375 76576500

Problem 11 In the 20×20 grid below, four numbers along a diagonal line have been marked in red.

08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48

The product of these numbers is 26 × 63 × 78 × 14 = 1788696.

What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?


In [32]:
path = 'p11.txt'
grid = []
highest = 0 
with open(path, 'r') as file:
    content = file.read().splitlines()
for x in content: 
    grid.append(x.rsplit(' '))
print(grid[3][3])
for x in range(20):
    for y in range(20):
    # check row 
        try:
            temp = int(grid[x][y]) * int(grid[x][y+1]) * int(grid[x][y+2]) * int(grid[x][y+3])
            if temp > highest: 
                highest = temp
                foo, bar = x,y
            temp = int(grid[x][y]) * int(grid[x+1][y]) * int(grid[x+2][y]) * int(grid[x+3][y])
            if temp > highest: 
                highest = temp
                foo, bar = x,y
            temp = int(grid[x][y]) * int(grid[x+1][y+1]) * int(grid[x+2][y+2]) * int(grid[x+3][y+3])
            if temp > highest: 
                highest = temp
                foo, bar = x,y
            temp = int(grid[x][y]) * int(grid[x-1][y+1]) * int(grid[x-2][y+2]) * int(grid[x-3][y+3])
            if temp > highest: 
                highest = temp
                foo, bar = x,y
        except:
            pass 
print(highest, foo, bar)


23
70600674 15 3

Problem 10 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. This took longer then I hoped. TODO - Think about optimizing


In [4]:
import math
def isPrime(anumber):
    if anumber ==  2:
        return(True)
    for x in range(2, int(math.sqrt(anumber))+1):     
        if anumber % x == 0:
            return(False)
    return(True)

top = 2000000
# top = 10 
count, total  = 1,2 # to account for the number 2 
for x in range(3,top, 2):
    if isPrime(x):
        count +=1 
        total = total + x 
print(count, total)


148933 142913828922

Day 3 - December 30

Problem 9 A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

aa + bb = c*c For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. Note: 3+ 4+ 5 = 12 and 3x4x5 = 60 Note: https://www.youtube.com/watch?v=B2FLARYs3bo Pick any two numbers M and N (with M > N) you get a Pythagorean Triple with A = M^2 - N^2, B = (MN)2 C = M^2 + N^2
So .... (M^2 - N^2) + (MN)2 + M^2 + N^2 = 1000


In [20]:
for m in range(100):
    for n in range(m-1):
        if (m* (m+n) == 500):
            print("We made it! ", m, n)
        if ((m*m) - (n*n)) + (2 * m * n) + ((m*m) + (n*n)) == 1000:
            print("What what", m, n) 
            print("A = ", ((m*m) - (n*n)), "B = ", (2 * m * n), "C=",((m*m) + (n*n)) )
            a = ((m*m) - (n*n))
            b = (2 * m * n)
            c = ((m*m) + (n*n)) 
            print("Sum = ", a + b + c)
            print("Product = ", a * b * c)
            break


We made it!  20 5
What what 20 5
A =  375 B =  200 C= 425
Sum =  1000
Product =  31875000

Problem 8 The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450

Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? Note: I think treating it like a string is the best


In [9]:
test = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
#test = '01234567899876543210'
length = len(test)
top = test[0:13]
topvalue = 0
for x in range(length):
    temp = test[x:x+13]
    product = 1 
    for y in temp: 
        product = product * int(y)
    if product > topvalue:
        topvalue = product 
        top = temp 
print("Value ", topvalue, "string ", top )


Value  23514624000 string  5576689664895

Problem 7 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?


In [5]:
import math
which = 10001
# which = 6 
x, count  = 1, 0
def isPrime(anumber):
    if anumber ==  2:
        return(True)
    for x in range(2, int(math.sqrt(anumber))+1):     
        if anumber % x == 0:
            return(False)
    return(True)

while count < which: 
    x += 1 
    if isPrime(x):
        count += 1 
print("The ", count, " prime is ", x)


The  10001  prime is  104743

Day 2 - December ??

Problem 6 The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.


In [87]:
num = 100
#num = 10 
total1,total2 = 0,0
for x in range(num,0,-1):
    total1 = total1 + x 
    total2 = total2 + (x*x)
print(total1* total1)
print(total2)
print((total1* total1) - total2)


25502500
338350
25164150

Problem 5 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Note: Set of all the factors


In [76]:
import math
top = 20
# top = 10 
total = 1 
for x in range(top, 1, -1):
    while total % x != 0:
        foo = math.gcd(total, x)
        total = int(total * (x/foo))
print(total)


232792560

Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.


In [22]:
tops = 999 * 999
bots = 698896    # 698896 
digits = 3
# tops = 99 * 99
# bots = 676 
# digits = 2

def isPalindromic(num):
    string = str(num)
    length = int(len(string)/2)
    # print("   num, string, len ", num, string, length)
    if string[length:][::-1] == string[:length]:
        return(True)
    return(False)
def isProductSize(num, digits):
    results = set()
    for i in range(1, int(num ** .5)+1):
        div, mod = divmod(num, i)
        if mod == 0:
            results |= {i, div}
            if len(str(i)) == digits and len(str(div)) == digits:
                print(i, div)
                return(True)
print('Tops', tops, 'bots ', bots, 'digits ', digits)
for x in range(tops, bots, -1 ): 
    if isPalindromic(x):
        # print("Yep, a palidrom ", x)
        if isProductSize(x, digits):
            print("The Highest Palindrom is ", x)
            break


Tops 998001 bots  698896 digits  3
913 993
The Highest Palindrom is  906609

In [21]:
isPalindromic(999999)


Out[21]:
True

Day 1 - December 27

Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000. You are the 715697th person to have solved this problem.


In [2]:
below = 1000
# below = 10 
total = 0
for x in range(below):
    if (x % 3 == 0) or (x % 5 == 0):
        total = total + x
print(total)


233168

Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.


In [8]:
top = 4000000
# top = 89 
first = 1 
second = 2
total, last = 0 , 0
while last < top:
    last = first + second 
    if last % 2 == 0:
        total = total + last
    first = second 
    second = last 
print("Total evens ", total + 2)
print("last, second, first", last, second, first)


Total evens  4613732
last, second, first 5702887 5702887 3524578

Problem 3 The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?

TODO: You could performance tune the hell out of this one. ie go through it in reverse until found.


In [20]:
import math
mynum = 600851475143 
# mynum = 13195
myprimes = []
top =  math.floor(math.sqrt(mynum))    # Does this need to be ceil instead 
print("Can not be divisible by more then sqrt", top)

def isPrime(anumber):
    if anumber < 2:
        return(False)
    for x in range(2, int(math.sqrt(anumber))+1):     # does this need to be sqrt + 1? 
        if anumber % x == 0:
            return(False)
    return(True)
for x in range(1, top, 2):
    if isPrime(x):
        if mynum % x == 0:
            myprimes.append(x)
# print(myprimes)
print("The highest prime factor ", max(myprimes))


Can not be divisible by more then sqrt 775146
6857

In [ ]: